<template>
  <div class="app-container">
    <el-row class="m-t-20 m-b-20 flex">
      <!-- <el-col :span="2">
        <div class="">
          <el-button type="primary" @click="goWenjuanModal">添加模板</el-button>
        </div>
      </el-col> -->

      <div class="p-b-15 m-r-15">
        <el-select v-model="value" filterable placeholder="请选择医院">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>


      <div class="p-b-15 m-r-15">
        <!-- <div class="m-r-15 nr" style="color: #606266;">筛选状态</div> -->
        <el-select v-model="StatusValue" placeholder="请选择状态">
          <el-option v-for="item in allStatus" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row class="m-b-15">
      <el-button type="primary" @click="goWenjuanModal">添加模板</el-button>
      <!-- <el-button type="primary" @click="goWenjuanModal">添加公共模板</el-button> -->
    </el-row>

    <el-table v-loading="loading" :data="titleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" :index="indexMethod" label="序号" fixd width="110"></el-table-column>
      <el-table-column prop="title" label="问卷名称">
      </el-table-column>

      <el-table-column prop="hospitalName" label="医院">
      </el-table-column>

      <el-table-column prop="answerNumber" label="答卷数">
      </el-table-column>

      <el-table-column prop="pageViews" label="浏览量">
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间">
      </el-table-column>

      <el-table-column prop="releaseTime" label="发布时间">
      </el-table-column>

      <el-table-column prop="updateTime" label="最新修改时间">
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.templat_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="220">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small">预览</el-button>
          <el-button type="text" size="small" @click="modify(scope.row)" v-if="scope.row.status == 2">修改</el-button>
          <!-- <el-button type="text" size="small" @click="handleUpdate(scope.row)">修改状态</el-button> -->

          <el-button type="text" size="small" @click="publish(scope.row)" v-if="scope.row.status == 2">发布</el-button>
          <el-button type="text" size="small" @click="copyModal(scope.row)" v-if="scope.row.status == 1">复制模板</el-button>
          <!-- <el-button type="text" size="small">暂停</el-button> -->
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改问卷模板管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="问卷标题(名称)" prop="title">
          <el-input v-model="form.title" disabled placeholder="请输入问卷标题(名称)" />
        </el-form-item>

        <el-form-item label="问卷类型" prop="statusLabel">
          <el-select v-model="form.status" placeholder="请选择问卷类型">
            <el-option v-for="dict in allStatus" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="问卷说明" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="运营科室" prop="operateDeptId">
          <el-input v-model="form.operateDeptId" placeholder="请输入运营科室" />
        </el-form-item>
        <el-form-item label="最新访问时间" prop="visitTime">
          <el-date-picker clearable v-model="form.visitTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择最新访问时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker clearable v-model="form.releaseTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="医院" prop="hosp">
          <el-input v-model="form.hosp" placeholder="请输入医院" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listTitle, getTitle, delTitle, addTitle, updateTitle, hosList, getModal, copyTemplate } from "@/api/hcem/title";
import { listData } from "@/api/system/dict/data";
export default {
  name: "Title",
  dicts: ['hcem_type', 'templat_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问卷模板管理表格数据
      titleList: [],
      // 弹出层标题
      title: "",
      section: [],//问卷，用于预览
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        title: null,
        description: null,
        operateDeptId: null,
        visitTime: null,
        releaseTime: null,
        hosp: null,
        status: null
      },
      rules: {
        type: [
          { required: true, message: "问卷类型不能为空", trigger: "change" }
        ]
      },
      // 表单参数
      form: {},
      options: [],
      value: '',
      allStatus: [
        // {
        //   value: '全部状态',
        //   label: '全部状态'
        // },
        // {
        //   value: '已发布',
        //   label: '已发布'
        // },
        // {
        //   value: '待发布',
        //   label: '待发布'
        // },
        // {
        //   value: '暂停发布',
        //   label: '暂停发布'
        // },
      ],
      StatusValue: '',
    };
  },
  watch: {
    // StatusValue(ne) {
    //   console.log(ne);
    //   this.getList()
    // }
  },
  created() {
    this.getStatus()
    this.getHosList()
    this.getList();
  },
  methods: {
    /** 查询问卷模板管理列表 */
    getList() {
      this.loading = true;
      this.titleList = []
      listTitle(this.queryParams).then(response => {
        // this.titleList = response.rows;
        // console.log(response);
        response.rows.forEach(v => {
          let findArr = this.options.find(params => params.value == v.hosp)
          //console.log(findArr,111);
          if (findArr !== undefined) v.hospitalName = findArr.label

          let LabelList = this.allStatus.find(params => {
            // console.log(params.value, 123, v.status);
            return params.value == v.status
          })
          // console.log(LabelList);
          if (LabelList !== undefined) v.statusLabel = LabelList.label

        })

        this.titleList.push(...response.rows)
        this.total = response.total;
        this.loading = false;
      });
    },
    publish(row) {
      if (row.status == 2) { //2待发布，然后点击后变已发布1
        this.$confirm(`确定要发布${row.title}吗？问卷发布后,不能编辑`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // console.log(444);
          // 用户点击了确定按钮，执行相应的操作  
          // 例如：删除文件、进行某种操作等  
          //  this.StatusValue = 1
          let params = {
            id: row.id,
            status: 1
          }
          updateTitle(params).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.getList();
          });

          // this.submitForm()
        }).catch(() => {
          // 用户点击了取消按钮，可以执行一些回滚操作  
          // 例如：撤销删除、恢复数据等  
        });
        //  console.log(row, 123);
      }

    },
    async copyModal(row) {
      this.$confirm(`确定复制：${row.title}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击了确定按钮，执行相应的操作  
        // 例如：删除文件、进行某种操作等  
        copyTemplate({ 'id': row.id }).then((result) => {
          this.getList();  //刷新列表
         // console.log(result, '666');
        })
        //  console.log(res);
        // console.log(555,row)
        // this.submitForm()
      }).catch(() => {
        // 用户点击了取消按钮，可以执行一些回滚操作  
        // 例如：撤销删除、恢复数据等  
      });


      //  console.log(row);
    },
    async getTest(row) {
      let id = row.id
      let res = await getModal(id)
      let a = res.data.hcemTemplatTopic.map(v => {
        let obj = JSON.parse(v.scoreInfo)
        obj.forEach(value => {
          value['pid'] = v.id
          value['answer'] = value.name
          value['scores'] = value.score
          value['flag'] = false
        })
        v.scoreInfo = obj
        this.section.push({
          project: {
            id: v.id,
            title: v.topicName, //标题
            describe: v.tip,//描述
            multipleValue: v.topicType.toString(),//单选多选值
            sectorValue: v.linkType == 0 ? '' : v.linkType, //环节
            isRequired: v.isRequired == 1 ? true : false,//是否必填
            sort: v.sort,    //优先级
            keyWord: v.keyWord, //关键词
            options: v.scoreInfo,
          }
        })
        // v.scoreInfo[k].pid = v.id
        //console.log(JSON.parse(v.scoreInfo));
        return v
      })
      // console.log(res.data.title, res.data.description);
      this.$store.state.hcem.section = this.section
      this.$store.state.hcem.qustionForm.title = res.data.title
      this.$store.state.hcem.qustionForm.content = res.data.description
      this.$router.push({ name: 'viewwenjuan' });
    },
    async handleClick(row) {
      await this.getTest(row)
      // console.log(row);
    },
    async getStatus() {
      let queryParams = {
        pageNum: 1,
        pageSize: 100,
        dictType: 'templat_status'
      }
      let res = await listData(queryParams)
      this.allStatus = res.rows.map(v => {
        //if(v.dictLabel == '已删除') return
        // console.log();
        return {
          value: v.dictValue,
          label: v.dictLabel
        }
      })
      this.allStatus = this.allStatus.filter(v => v.label !== '已删除' && v.label !== '暂停接收')
      // this.allStatus.unshift({
      //   value: '',
      //   label: '全部状态'
      // })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('确认删除: ' + row.title).then(function () {
        return delTitle(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hcem/title/export', {
        ...this.queryParams
      }, `title_${new Date().getTime()}.xlsx`)
    },
    indexMethod(index) {
      return ++index;
    },
    async getTableList() {
      let res = await listTitle()
      res.data.rows.forEach(v => {
        let findArr = this.options.find(params => params.value == v.hosp)
        //console.log(findArr,111);
        if (findArr !== undefined) v.hospitalName = findArr.label

      })
      this.titleList.push(...res.data.rows)
      // console.log(res.data.rows, 111);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTitle(id).then(response => {
        // console.log(response);
        let LabelList = this.allStatus.find(params => {
          // console.log(params.value, 123, response.data.status);
          return params.value == response.data.status
        })
        // console.log(LabelList);
        //  this.$nextTick(()=>{
        if (LabelList !== undefined) response.data.statusLabel = LabelList.label
        //  })
        //console.log(response.data);
        this.form = response.data;
        this.open = true;
        this.title = "修改问卷模板管理";
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        title: null,
        description: null,
        operateDeptId: null,
        visitTime: null,
        releaseTime: null,
        hosp: null,
        createTime: null,
        updateTime: null,
        status: null
      };
      this.resetForm("form");
    },
    async getHosList() {
      let res = await hosList()
      let data = res.data
      data.forEach(v => {
        this.options.push({
          value: v.hospital_code,
          label: v.hospital_name
        })
      })
      // this.options.unshift({
      //   value: '',
      //   label: '全部医院'
      // })
      // console.log(res);
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        let params = {
          id: this.form.id,
          status: this.form.status
        }
        if (valid) {
          if (this.form.id != null) {
            updateTitle(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTitle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    goWenjuanModal() {
      if (!this.value) {
        this.$message('请选择医院');
        return
      }
      this.$router.push({ name: 'wenjuanTpl', query: { 'hosp': this.value } })
    },
    modify(row, action = 'modify') {
      this.$router.push({ name: 'wenjuanTplModify', query: { 'id': row.id, 'action': action, 'hosp': row.hosp } })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.hosp = this.value
      this.queryParams.status = this.StatusValue
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      this.queryParams.hosp = ''
      this.queryParams.status = ''
      this.value = ''
      this.StatusValue = ''
      this.getList();
    },
  },

};
</script>

<style>
.el-table__body-wrapper::-webkit-scrollbar {
  width: 8px;
  /*滚动条宽度*/
  height: 8px;
  /*滚动条高度*/
}

.el-table__body-wrapper::-webkit-scrollbar-track {
  border-radius: 10px;
  /*滚动条的背景区域的圆角*/
  -webkit-box-shadow: inset 0 0 6px rgba(238, 238, 238, 0.3);
  background-color: #eeeeee;
  /*滚动条的背景颜色*/
}

.el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 10px;
  /*滚动条的圆角*/
  -webkit-box-shadow: inset 0 0 6px rgba(145, 143, 0143, 0.3);
  background-color: rgb(145, 143, 143);
  /*滚动条的背景颜色*/
}
</style>
